// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext()
	let returnData = {
		code: 1,
		msg: "",
		data: ""
	}

	let _user = await db.collection('user').where({
		_openid: wxContext.OPENID
  }).get()

	if (_user && _user.data && _user.data.length > 0) returnData.data = _user.data[0]
	else {
		if (!event.nickName) {
			returnData.code = 0
			returnData.msg = "请输入昵称"
		} else {
			let result = await db.collection('user').add({
				// data 字段表示需新增的 JSON 数据
				data: {
					avatarUrl: event.avatarUrl,
					nickName: event.nickName,
					_openid: wxContext.OPENID
				}
			})
			returnData.data = result
		}
	}


	return returnData
}